package com.wd.mylibrary_base.base

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.wd.mylibrary_base.R
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VM:ViewModel,D:ViewDataBinding>(private var layoutId:Int) : Fragment() {

    lateinit var dataBinding:D
    lateinit var viewModel:VM
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        dataBinding=DataBindingUtil.inflate(inflater,layoutId, container, false)
        dataBinding.lifecycleOwner=this
        return dataBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        var type = javaClass.genericSuperclass as ParameterizedType
        var ClassVM = type.actualTypeArguments[0] as Class<VM>
        viewModel = ViewModelProvider(this)[ClassVM]
        initViews()
        dataObserver()

    }

    abstract fun dataObserver()
    abstract fun initViews()

    override fun onDestroy() {
        super.onDestroy()
        if(dataBinding!=null) dataBinding.unbind()
    }

}